package com.witmore.skyline.web.service.messagehandler;


import com.witmore.skyline.web.controller.api.CloudmMessageParam;
import com.witmore.skyline.web.service.messagehandler.handler.MessageHandlesType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class MessageProcessor {
    private final Map<MessageType, MessageHandler> hanlderMap;

    @Autowired
    public MessageProcessor(List<MessageHandler> handlers) {
        hanlderMap = new HashMap<>();
        handlers.forEach(handler -> {
            MessageHandlesType annotation = handler.getClass().getAnnotation(MessageHandlesType.class);
            if (annotation != null) {
                hanlderMap.put(annotation.value(), handler);
            }
        });

    }

    @Async("threadPoolExecutor")
    public void processMessage(CloudmMessageParam param) {
        try {
            MessageType type = MessageType.valueOf(param.getMessageType());
            MessageHandler handler = hanlderMap.get(type);
            handler.handlerMessage(param);
        } catch (Exception e) {
            log.error("接收云机械消息异步处理失败", e);
        }
    }

}
